public class BinarySearchTree {
    //节点的静态内部类
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root = null;
    public boolean search(int val) {
        TreeNode cur = root;
        while(cur != null) {
            if (cur.val > val) {
                cur = cur.left;
            } else if (cur.val < val) {
                cur = cur.right;
            } else {
                return true;
            }
        }
        return false;
    }
    public void insert(int val) {
        if(root == null) {
            root = new TreeNode(val);
            return ;
        }
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null) {
            if(cur.val < val) {
                parent = cur;
                cur = cur.right;
            }else if(cur.val > val) {
                parent = cur;
                cur = cur.left;
            }else {
                return ;
            }
        }
        //到插入了
        if(parent.val > val) {
            parent.left = new TreeNode(val);
        }else {
            parent.right = new TreeNode(val);
        }
    }

    public void remove(int val) {
        TreeNode cur = root;
        TreeNode parent = null;
        while(cur != null) {
            if(cur.val < val) {
                parent = cur;
                cur = cur.right;
            }else if(cur.val > val) {
                parent = cur;
                cur = cur.left;
            }else {
                removeNode(cur,parent);
                return ;
            }
        }
    }

    private void removeNode(TreeNode cur, TreeNode parent) {
        if(cur.left == null) {
            //cur 的右节点为空
            if(cur == root) {
                root = cur.right;
            }else if(cur == parent.left) {
                parent.left = cur.right;
            }else {
                parent.right = cur.right;
            }
        }else if(cur.right == null) {
            //cur 的左节点为空
            if(cur == root) {
                root = cur.left;
            }else if(cur == parent.left) {
                parent.left = cur.left;
            }else {
                parent.left = cur.left;
            }
        }else {
            //cur 的左右节点都不为空
            parent = cur.left;
            TreeNode parentNode = cur;
            //找左边最大值
            while(parent.right != null) {
                parentNode = parent;
                parent = parent.right;
            }
            //现在parent是左边的最大值开始替换
            cur.val = parent.val;
            if(parent == parentNode.right) {
                parentNode.right = parent.right;
            }else {
                parentNode.left = parent.left;
            }
        }
    }

}
